package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //如果本次请求的目标资源不是Controller里的方法，则直接放行，不需要处理
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取本次请求携带的令牌
        String token = request.getHeader("authorization");

        //如果令牌为空，返回401
        if(StringUtils.isEmpty( token)){
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }

        //开始解析令牌
        Claims claims = tokenService.parseToken( token);
        if(ObjectUtil.isEmpty(claims)){
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }

        //获取令牌中的用户信息
        Long userId = claims.get("userId", Long.class);
        //没找到用户信息，认证失败
        if(userId == null){
            response.setStatus(401);
            log.warn("认证失败");
            return false;
        }
        //认证成功，将id绑定到线程上
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //使用完成，将线程上绑定的用户id清除
        UserThreadLocal.remove();
    }
}
